package nio.selector;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;

/**
 * @author 张开顺
 * @title: SelectorServer
 * @projectName netty
 * @description: TODO
 * @date 2019/4/129:13
 */
public class SelectorServer {
    private static final int PORT = 1234;
    private static ByteBuffer buffer = ByteBuffer.allocate(1024);


    public static void main(String[] args) throws Exception {

        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        serverSocketChannel.socket().bind(new InetSocketAddress("127.0.0.1",PORT));
        serverSocketChannel.configureBlocking(false);//非阻塞模式

        Selector selector = Selector.open();
        serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
        System.out.println("REGISTER CHANNEL , CHANNEL NUMBER IS:" + selector.keys().size());

        while (true) {
            int n = selector.select();
            if (n == 0) {
                continue;
            }
            Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
            while (iterator.hasNext()) {
                SelectionKey key = iterator.next();
                if (key.isAcceptable()) {//连接就绪  如果满足Acceptable条件，则必定是一个ServerSocketChannel
                    ServerSocketChannel sscTemp = (ServerSocketChannel) key.channel();
                    //得到一个连接好的SocketChannel，并把它注册到Selector上，兴趣操作为READ
                    SocketChannel socketChannel = sscTemp.accept();
                    socketChannel.configureBlocking(false);
                    socketChannel.register(selector, SelectionKey.OP_READ);
                    System.out.println("REGISTER CHANNEL , CHANNEL NUMBER IS:" + selector.keys().size());
                }
                if (key.isReadable()) {
                    SocketChannel socketChannel = (SocketChannel) key.channel();
                    readFromChannel(socketChannel);
                }
                iterator.remove();
            }


        }
    }

        private static void readFromChannel(SocketChannel channel) {
            buffer.clear();
            try {
                while (channel.read(buffer) > 0) {
                    buffer.flip();
                    byte[] bytes = new byte[buffer.remaining()];
                    buffer.get(bytes);
                    System.out.println("read from " + new String(bytes));
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
}
